package handler

import (
	"github.com/gin-gonic/gin"
	"house/api/request"
	"house/api/resp"
	"house/internal/dao"
	"house/internal/model"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrder
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if user.TypeUser != 1 {
		resp.Error(c, 100000, "需买家权限", false)
		return
	}

	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		resp.Error(c, 100000, "该房源不存在", false)
		return
	}
	result := dao.Create(&model.Order{
		UserId:  c.GetUint("userId"),
		HouseId: req.HouseId,
		Price:   house.Price,
	})
	if !result {
		resp.Error(c, 100000, "用户下单失败", false)
		return
	}
	dao.Update(&model.House{
		Id:     req.HouseId,
		Status: 4,
	})

	resp.Success(c, "用户下单成功", true)
}

func UpLoadPay(c *gin.Context) {
	var req request.UpLoadPay
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var order model.Order
	dao.GetOneById(req.Id, &order)
	if order.Id == 0 {
		resp.Error(c, 100000, "该订单不存在", false)
		return
	}
	if order.UserId != c.GetUint("userId") {
		resp.Error(c, 100000, "需买家上传", false)
		return
	}
	result := dao.Update(&model.Order{
		Id:     req.Id,
		PayUrl: req.PayUrl,
	})
	if !result {
		resp.Error(c, 100000, "用户上传失败", false)
		return
	}
	resp.Success(c, "用户上传成功", true)

}
